package com.codechuan.didi_web.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.codechuan.didi_web.common.Constant;
import com.codechuan.didi_web.entity.*;
import com.codechuan.didi_web.mapper.SysUserOrderMapper;
import com.codechuan.didi_web.mapper.SysUserTokenMapper;
import com.codechuan.didi_web.thread.SubMitOrder;
import com.codechuan.didi_web.vo.ResultVO;
import okhttp3.*;
import okhttp3.Authenticator;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.codechuan.didi_web.service.impl.ThreadManagerServiceImpl.getRandomAlphanumeric;
import static com.codechuan.didi_web.thread.GetAnOrderThread.getMD5;
import static com.codechuan.didi_web.utils.JSUtil.executeJs;
import static com.codechuan.didi_web.utils.JSUtil.extractFunctionName;

public class DiDiHttpUtil {
    private static final String secretId = "otdn4vnfgj5wacvvvokl";
    private static final String signature = "702hr511l1gn51kzphaxhx0sicvncw31";
    private static final String urlString = "https://dps.kdlapi.com/api/getdps/?secret_id=" + secretId + "&signature=" + signature + "&num=1&pt=1&format=text&sep=1";

    /**
     * @param url 请求地址
     * @Deprecated DD04接口调用
     */
    public String getDD04(String url, String body) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url("http://27.25.139.151:30000/dd/cal?url=" + url + "&body=" + body)
                .build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            assert response.body() != null;
            return response.body().string();
        }
    }


    /**
     * @param hashMap              请求参数
     * @param token                token
     * @param secdd_authentication 用户认证信息
     * @param secdd_challenge      js算法
     * @param mog_id               随机生成的
     * @param uuid                 随机生成的
     * @param account              启动该方法的用户
     * @Deprecated 取大厅订单_跨城
     */
    public HashMap<String, String> getACrossCityOrderInTheLobby(HashMap<String, Object> hashMap, String token, String miniTicket,
                                                                String dd04, String secdd_authentication,
                                                                String secdd_challenge, String mog_id, String uuid, String account,
                                                                ArrayList<String> acquiredOrders, SysCarInfo carInfo,
                                                                SysUserOrderMapper sysUserOrderMapper,
                                                                SysUserConfig sysUserConfig, RedisTemplate redisTemplate,
                                                                SysUserTokenMapper sysUserTokenMapper) {
        String now = Constant.format.format(new Date());
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("https://api.udache.com/gulfstream/hermesapi/v2/driver/dBusinessOrderList")
                .post(body)
                .addHeader("Content-Type", "application/json;charset=UTF-8")
                .addHeader("ticket", miniTicket)
                .addHeader("didi-header-omgid", mog_id)
                .addHeader("didi-header-ssuuid", uuid)
                .addHeader("secdd-authentication", secdd_authentication)
                .addHeader("Productid", "0")
                .addHeader("secdd-challenge", secdd_challenge)
                .addHeader("secdd-challenge", secdd_challenge)
                .addHeader("Host", "api.udache.com")
                .addHeader("TripCountry", "CN")
                .addHeader("wsgsig", dd04)
                .addHeader("didi-header-rid", uuid)
                .addHeader("CityId", String.valueOf(sysUserConfig.getCityId()))
                .addHeader("User-Agent", "didihttp OneNet/3.0.3-TO-RABBIT com.sdu.didi.psnger/6.8.8")
                .addHeader("didi-httpdns", "1")
                .addHeader("Connection", "close")
                .build();

        // 发送请求并获取响应
        try (Response response = client.newCall(request).execute()) {
            HashMap<String, String> hashMap1 = new HashMap<>();
            // 获取响应头
            String authentication = response.header("secdd-authentication");
            if (authentication != null && !authentication.isEmpty()) {
                secdd_authentication = authentication;
                hashMap1.put("secdd_authentication", secdd_authentication);
            }
            String sessionid = response.header("set-secch-sessionid");
            if (sessionid != null && !sessionid.isEmpty()) {
                String pattern = "(?<=secch_sessionid=)[0-9a-m]+"; // 正则表达式
                Pattern p = Pattern.compile(pattern);
                Matcher m = p.matcher(sessionid);
                if (m.find()) {
                    secdd_challenge = "1,com.sdu.didi.psnger|1.0.28||||0||" + m.group();
                    hashMap1.put("secdd_challenge", secdd_challenge);
                }
            }
            assert response.body() != null;
            JSONObject jsonObject = null;
            try {
                jsonObject = JSONObject.parseObject(response.body().string());
            } catch (Exception e) {
                System.out.println("解析JSON错误");
                return resultMap();
            }
            JSONObject data = JSONObject.parseObject(jsonObject.getString("data"));
            String code = jsonObject.getString("code");
            if (code != null && code.equals("0")) {
                String func_def = data.getString("func_def");
                String func = data.getString("func");
                String args = data.getString("args");
                String chid = data.getString("chid");
                String ts = data.getString("ts");
                String res = executeJs(func_def, extractFunctionName(func_def), args);
                secdd_challenge = "1,com.sdu.didi.psnger|1.0.28" + "|" + func + "|" + args + "|" + ts + "|" + res + "|" + chid + "|";
                hashMap1.put("secdd_challenge", secdd_challenge);
                return hashMap1;
            } else {
                if (jsonObject.getString("errno") != null && jsonObject.getString("errno").equals("5555555")) {
                    System.out.println(now + "大厅刷新订单过快");
                    // todo更新账户状态
                    sysUserTokenMapper.updateStatusByToken(miniTicket, "刷新过快");
                } else {
                    JSONArray jsonArray = data.getJSONArray("passenger_cards");
                    if (jsonArray == null) {
                        return resultMap();
                    }
                    boolean isOk = false;
                    for (Object passengerCards : jsonArray) {
                        JSONObject listData = JSONObject.parseObject(passengerCards.toString());
                        JSONObject invite_params = listData.getJSONObject("invite_button").getJSONObject("invite_params");
                        String string = invite_params.getString("route_id");
                        String group_key = invite_params.getString("group_key");
                        String from_lat = invite_params.getString("from_lat");
                        String from_lng = invite_params.getString("from_lng");
                        String to_lat = invite_params.getString("to_lat");
                        String to_lng = invite_params.getString("to_lng");
                        String from_address = invite_params.getString("from_address");
                        String starting_poi_id = invite_params.getString("starting_poi_id");
                        String sess_id = invite_params.getString("sess_id");
                        String from_source = invite_params.getString("from_source");
                        String from_city_id = invite_params.getString("from_city_id");
                        JSONObject orderInfo = listData.getJSONObject("order_info");
                        // 出发位置 广州市·焕新医疗美容
                        String from_name = orderInfo.getString("from_name");
                        // 终点位置 深圳市·深圳金福林酒店
                        String to_name = orderInfo.getString("to_name");
                        // 距离乘客距离 0.9km
                        String from_dist = orderInfo.getString("from_dist");
                        // 接单需要的orderId
                        String oid = orderInfo.getString("oid");


                        JSONArray tag_list = listData.getJSONArray("tag_list");
                        // 拼单或独享 {"text":"{1人愿拼}"}
                        String pcDxString = extractContent(JSONObject.parseObject(tag_list.getString(0)).getString("text"));

                        // 订单里程 {"text":"订单里程132.7km"}
                        String order_des = tag_list.getString(1);
                        order_des = JSONObject.parseObject(tag_list.getString(1)).getString("text");
                        String replace = order_des.replaceAll("订单里程", "").replace("km", "");
                        if (Double.valueOf(replace) > sysUserConfig.getZdjl()) {
                            continue;
                        }

                        // 出发时间 明天{00:20-00:35}
                        String start_date = listData.getJSONObject("time_range").getString("start_date");
                        String price = listData.getJSONObject("price_info").getString("title");
                        price = extractContent(price).replaceAll("元", "");

                        // 校验开始
                        // 出发时间校验 如果勾选只接今天那么就不判断时间只判断 start_date中的今天 明天 大后天
                        String startTime = sysUserConfig.getStartTime();
                        String endTime = sysUserConfig.getEndTime();

                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
                        LocalDateTime startLocalTime = LocalDateTime.parse(startTime, formatter);
                        LocalDateTime endLocalTime = LocalDateTime.parse(endTime, formatter);
                        LocalDateTime orderLocalTime = LocalDateTime.parse(parseTime(start_date), formatter);

                        // 判断订单时间时间是否早于设置的开始时间
                        int comparisonResultOne = orderLocalTime.compareTo(startLocalTime);
                        if (comparisonResultOne < 0 && sysUserConfig.getZqJtCheckBox().equals("false")) {
                            continue;
                        }
                        // 判断订单时间时间是否晚于设置的结束时间
                        int comparisonResultTwo = orderLocalTime.compareTo(endLocalTime);
                        if (comparisonResultTwo > 0 && sysUserConfig.getZqJtCheckBox().equals("false")) {
                            continue;
                        }

                        // 价格校验规则
                        if (Double.valueOf(price) < Integer.valueOf(sysUserConfig.getMinMoney()))
                            continue;
                        if (Double.valueOf(price) > Integer.valueOf(sysUserConfig.getMaxMoney()))
                            continue;

                        // 接客距离校验规则
                        String startDes = from_dist.replaceAll("km", "");
                        if (Double.parseDouble(startDes) > Integer.valueOf(sysUserConfig.getJkJl()))
                            continue;

                        // 接单独享校验规则
                        if (sysUserConfig.getDxCheckBox().equals("true") && pcDxString.contains("人独享")) {
                            String replaced = pcDxString.replaceAll("人独享", "");
                            if (Integer.valueOf(replaced) < Integer.valueOf(sysUserConfig.getMinDxPerson()))
                                continue;
                            if (Integer.valueOf(replaced) > Integer.valueOf(sysUserConfig.getMaxDxPerson()))
                                continue;
                        }
                        // 如果是没有勾选独享那么单子是独享就直接跳过免得胡乱接单
                        if (sysUserConfig.getDxCheckBox().equals("false") && pcDxString.contains("人独享"))
                            continue;

                        // 接单拼车校验规则
                        if (sysUserConfig.getPcCheckBox().equals("true") && pcDxString.contains("人愿拼")) {
                            String replaced = pcDxString.replaceAll("人愿拼", "");
                            if (Integer.valueOf(replaced) < Integer.valueOf(sysUserConfig.getMinPcPerson()))
                                continue;
                            if (Integer.valueOf(replaced) > Integer.valueOf(sysUserConfig.getMaxPcPerson()))
                                continue;
                        }
                        // 如果是没有勾选拼车那么单子是拼车就直接跳过免得胡乱接单
                        if (sysUserConfig.getPcCheckBox().equals("false") && pcDxString.contains("人愿拼"))
                            continue;

                        // 只接今天 校验规则
                        if (sysUserConfig.getZqJtCheckBox().equals("true")) {
                            if (!start_date.contains("今天"))
                                continue;
                        }


                        SysSuccessOrder sysSuccessOrder = new SysSuccessOrder();
                        sysSuccessOrder.setOrderId(oid);
                        sysSuccessOrder.setGroupKey(group_key);
                        sysSuccessOrder.setRouteId(null);
                        sysSuccessOrder.setLat(from_lat);
                        sysSuccessOrder.setLng(from_lng);
                        sysSuccessOrder.setToLat(to_lat);
                        sysSuccessOrder.setRouteId(string);
                        sysSuccessOrder.setToLng(to_lng);
                        sysSuccessOrder.setFromCityId(from_city_id);
                        sysSuccessOrder.setStartingPoiId(starting_poi_id);
                        sysSuccessOrder.setFromName(from_name);
                        sysSuccessOrder.setFromSource(from_source);
                        sysSuccessOrder.setSessId(sess_id);
                        sysSuccessOrder.setFromAddress(from_address);
                        sysSuccessOrder.setOrderDes(order_des);
                        sysSuccessOrder.setPrice(price);
                        sysSuccessOrder.setOrderType("大厅");
                        sysSuccessOrder.setTicket(token);
                        sysSuccessOrder.setSysCarInfo(carInfo);
                        if (isOk)
                            break;
                        String setUpTime = getOrderSetUpTime(sysSuccessOrder.getTicket(), sysSuccessOrder);
                        JSONObject inviteResult = invitePeersCrossCity(sysSuccessOrder, setUpTime, token, secdd_authentication, secdd_challenge, String.valueOf(sysUserConfig.getCityId()));
                        String inviteResult1 = inviteResult.getString("invite_result");
                        String status = "";
                        if (inviteResult1.equals("1")) {
                            System.out.println(start_date);
                            status = "抢单成功";
                            // 设置抢单状态
                            redisTemplate.opsForValue().set(account, "isStart:0");
                            System.out.println("抢单成功" + inviteResult);
                            isOk = true;
                        } else {
                            System.out.println("抢单失败" + inviteResult);
                            String toast = inviteResult.getString("toast");
                            if (toast == null || toast.isEmpty()) {
                                status = "该订单被滴滴指定派送了";
                            } else {
                                status = toast;
                            }
                        }
                        // 存入数据库
                        SysUserOrder sysUserOrder = new SysUserOrder();
                        sysUserOrder.setOrderId(sysSuccessOrder.getOrderId());
                        sysUserOrder.setRouteId(sysUserOrder.getRouteId());
                        sysUserOrder.setOrderStatus(sysSuccessOrder.getOrderId());
                        sysUserOrder.setPrice(sysSuccessOrder.getPrice());
                        sysUserOrder.setPersonNumber(pcDxString);
                        sysUserOrder.setOrderDes(order_des);
                        sysUserOrder.setOrderType("大厅");
                        sysUserOrder.setCreateTime(new Date());
                        sysUserOrder.setAccount(account);
                        sysUserOrder.setOrderStatus(status);
                        sysUserOrder.setStartAddress(from_name);
                        sysUserOrder.setEndAddress(to_name);
                        sysUserOrder.setStartDes(from_dist);
                        sysUserOrderMapper.insert(sysUserOrder);
                    }
                    //System.out.println(account + "的" + miniTicket + "在" + now + "大厅刷新到:" + data.getJSONArray("passenger_cards").size());
                }
                return hashMap1;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }



    /**
     * @param hashMap              请求参数
     * @param token                token
     * @param secdd_authentication 用户认证信息
     * @param secdd_challenge      js算法
     * @param mog_id               随机生成的
     * @param uuid                 随机生成的
     * @param account              启动该方法的用户
     * @Deprecated 取行程订单
     */
    public HashMap<String, String> getScheduleOrdrList(String ticket, String mog_id,
                                                       String dd04,
                                                       String uuid,
                                                       String secdd_authentication,
                                                       String secdd_challenge,
                                                       String route_id,
                                                       String account, SysCarInfo carInfo,
                                                       ArrayList<String> acquiredOrders,
                                                       SysUserOrderMapper sysUserOrderMapper,
                                                       SysUserConfig sysUserConfig, RedisTemplate redisTemplate) {
        String now = Constant.format.format(new Date());
        OkHttpClient client = new OkHttpClient();
        String token = URLEncoder.encode(ticket);
        String url = "https://api.udache.com/gulfstream/hermesapi/v2/driver/dSfcDriverList?session_id=0&route_id=" + route_id
                + "&page_type=&page_index=0&session_id=0&access_key_id=2&app_version=6.8.12&ddfp=" + uuid + "&token=" + token;
        Request.Builder requestBuilder = new Request.Builder().url(url);
        // 添加自定义请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("ticket", token);
        headers.put("didi-header-omgid", mog_id);
        headers.put("didi-header-ssuuid", uuid);
        headers.put("authentication", secdd_authentication);
        headers.put("Productid", "0");
        headers.put("secdd-challenge", secdd_challenge);
        headers.put("Host", "api.udache.com");
        headers.put("Connection", "Keep-Alive");
        headers.put("TripCountry", "CN");
        headers.put("wsgsig", dd04);
        headers.put("didi-header-rid", uuid);
        headers.put("CityId", String.valueOf(sysUserConfig.getCityId()));
        headers.put("User-Agent", "com.sdu.didi.psnger/6.8.12 Rabbit/1.2.6.5 Carrot/1.3.5");
        headers.put("didi-httpdns", "1");
        headers.forEach(requestBuilder::addHeader);
        // 构建完整的请求
        Request request = requestBuilder.build();
        // 发送请求并获取响应
        try (Response response = client.newCall(request).execute()) {
            HashMap<String, String> hashMap1 = new HashMap<>();
            // 获取响应头
            String authentication = response.header("secdd-authentication");
            if (authentication != null && !authentication.isEmpty()) {
                secdd_authentication = authentication;
                hashMap1.put("secdd_authentication", secdd_authentication);
            } else {
                hashMap1.put("secdd_authentication", secdd_authentication);
            }
            String sessionid = response.header("set-secch-sessionid");
            if (sessionid != null && !sessionid.isEmpty()) {
                String pattern = "(?<=secch_sessionid=)[0-9a-m]+"; // 正则表达式
                Pattern p = Pattern.compile(pattern);
                Matcher m = p.matcher(sessionid);
                if (m.find()) {
                    secdd_challenge = "1,com.sdu.didi.psnger|1.0.28||||0||" + m.group();
                    hashMap1.put("secdd_challenge", secdd_challenge);
                }
            }
            assert response.body() != null;
            JSONObject jsonObject = null;
            try {
                jsonObject = JSONObject.parseObject(response.body().string());
            } catch (Exception e) {
                System.out.println("解析JSON错误");
                return resultMap();
            }
            JSONObject data = JSONObject.parseObject(jsonObject.getString("data"));
            String code = jsonObject.getString("code");
            if (code != null && code.equals("0")) {
                String func_def = data.getString("func_def");
                String func = data.getString("func");
                String args = data.getString("args");
                String chid = data.getString("chid");
                String ts = data.getString("ts");
                String res = executeJs(func_def, extractFunctionName(func_def), args);
                secdd_challenge = "1,com.sdu.didi.psnger|1.0.28" + "|" + func + "|" + args + "|" + ts + "|" + res + "|" + chid + "|";
                hashMap1.put("secdd_challenge", secdd_challenge);
                return hashMap1;
            } else {
                if (data == null)
                    return hashMap1;
                if (data.getString("title") != null && data.getString("title").equals("抱歉，行程已超时")) {
                    System.out.println(now + "抱歉，行程已超时");
                    return hashMap1;
                }
                if (jsonObject.getString("errno") != null && jsonObject.getString("errno").equals("5555555")) {
                    System.out.println(now + "行程刷新订单过快");
                } else {
                    JSONArray jsonArray = data.getJSONArray("passenger_cards");
                    if (jsonArray == null) {
                        return resultMap();
                    }
                    boolean isOk = false;
                    for (Object passengerCards : jsonArray) {
                        JSONObject listData = JSONObject.parseObject(passengerCards.toString());
                        JSONObject invite_params = listData.getJSONObject("invite_button").getJSONObject("invite_params");
                        // 接单需要的行程id
                        String routeId = invite_params.getString("route_id");
                        // 接单需要的key
                        String group_key = invite_params.getString("group_key");
                        // 接单需要的经纬度
                        String from_lat = invite_params.getString("from_lat");
                        String from_lng = invite_params.getString("from_lng");
                        String to_lat = invite_params.getString("to_lat");
                        String to_lng = invite_params.getString("to_lng");
                        String from_address = invite_params.getString("from_address");
                        String starting_poi_id = invite_params.getString("starting_poi_id");
                        String sess_id = invite_params.getString("sess_id");
                        String from_source = invite_params.getString("from_source");
                        String from_city_id = invite_params.getString("from_city_id");
                        JSONObject orderInfo = listData.getJSONObject("order_info");
                        // 出发位置 广州市·焕新医疗美容
                        String from_name = orderInfo.getString("from_name");
                        // 终点位置 深圳市·深圳金福林酒店
                        String to_name = orderInfo.getString("to_name");
                        // 距离乘客距离 0.9km
                        String from_dist = orderInfo.getString("from_dist");
                        // 接单需要的orderId
                        String oid = orderInfo.getString("oid");
                        // 如果订单重复进来则不执行for循环
                        if (acquiredOrders.contains(oid)) {
                            continue;
                        }
                        // 加入重复订单
                        acquiredOrders.add(oid);
                        JSONArray tag_list = listData.getJSONArray("tag_list");
                        // 拼单或独享 {"text":"{1人愿拼}"}
                        String pcDxString = extractContent(JSONObject.parseObject(tag_list.getString(0)).getString("text"));

                        // 订单里程 {"text":"订单里程132.7km"}
                        String order_des = tag_list.getString(1);
                        order_des = JSONObject.parseObject(tag_list.getString(1)).getString("text");
                        String replace = order_des.replaceAll("订单里程", "").replace("km", "");
                        if (Double.valueOf(replace) > sysUserConfig.getZdjl()) {
                            continue;
                        }
                        // 出发时间 明天{00:20-00:35}
                        String start_date = listData.getJSONObject("time_range").getString("start_date");
                        // 顺利度
                        String degree = listData.getJSONObject("match_card").getString("degree");

                        String price = listData.getJSONObject("price_info").getString("title");
                        price = extractContent(price).replaceAll("元", "");

                        // 校验开始
                        // 判断只接城市
                        if (!sysUserConfig.getZdcs().contains(from_name)) {
                            continue;
                        }
                        // 出发时间校验 如果勾选只接今天那么就不判断时间只判断 start_date中的今天 明天 大后天
                        String startTime = sysUserConfig.getStartTime();
                        String endTime = sysUserConfig.getEndTime();

                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
                        LocalDateTime startLocalTime = LocalDateTime.parse(startTime, formatter);
                        LocalDateTime endLocalTime = LocalDateTime.parse(endTime, formatter);
                        LocalDateTime orderLocalTime = LocalDateTime.parse(parseTime(start_date), formatter);

                        // 判断订单时间时间是否早于设置的开始时间
                        int comparisonResultOne = orderLocalTime.compareTo(startLocalTime);
                        if (comparisonResultOne < 0 && sysUserConfig.getZqJtCheckBox().equals("false")) {
                            continue;
                        }
                        // 判断订单时间时间是否晚于设置的结束时间
                        int comparisonResultTwo = orderLocalTime.compareTo(endLocalTime);
                        if (comparisonResultTwo > 0 && sysUserConfig.getZqJtCheckBox().equals("false")) {
                            continue;
                        }

                        // 价格校验规则
                        if (Double.valueOf(price) < Integer.valueOf(sysUserConfig.getMinMoney()))
                            continue;
                        if (Double.valueOf(price) > Integer.valueOf(sysUserConfig.getMaxMoney()))
                            continue;

                        // 接客距离校验规则
                        String startDes = from_dist.replaceAll("km", "");
                        if (Double.parseDouble(startDes) > Integer.valueOf(sysUserConfig.getJkJl()))
                            continue;

                        // 接单独享校验规则
                        if (sysUserConfig.getDxCheckBox().equals("true") && pcDxString.contains("人独享")) {
                            String replaced = pcDxString.replaceAll("人独享", "");
                            if (Integer.valueOf(replaced) < Integer.valueOf(sysUserConfig.getMinDxPerson()))
                                continue;
                            if (Integer.valueOf(replaced) > Integer.valueOf(sysUserConfig.getMaxDxPerson()))
                                continue;
                        }
                        // 如果是没有勾选独享那么单子是独享就直接跳过免得胡乱接单
                        if (sysUserConfig.getDxCheckBox().equals("false") && pcDxString.contains("人独享"))
                            continue;

                        // 接单拼车校验规则
                        if (sysUserConfig.getPcCheckBox().equals("true") && pcDxString.contains("人愿拼")) {
                            String replaced = pcDxString.replaceAll("人愿拼", "");
                            if (Integer.valueOf(replaced) < Integer.valueOf(sysUserConfig.getMinPcPerson()))
                                continue;
                            if (Integer.valueOf(replaced) > Integer.valueOf(sysUserConfig.getMaxPcPerson()))
                                continue;
                        }
                        // 如果是没有勾选拼车那么单子是拼车就直接跳过免得胡乱接单
                        if (sysUserConfig.getPcCheckBox().equals("false") && pcDxString.contains("人愿拼"))
                            continue;

                        // 只接今天 校验规则
                        if (sysUserConfig.getZqJtCheckBox().equals("true")) {
                            if (!start_date.contains("今天"))
                                continue;
                        }

                        SysSuccessOrder sysSuccessOrder = new SysSuccessOrder();
                        sysSuccessOrder.setOrderId(oid);
                        sysSuccessOrder.setGroupKey(group_key);
                        sysSuccessOrder.setRouteId(null);
                        sysSuccessOrder.setLat(from_lat);
                        sysSuccessOrder.setLng(from_lng);
                        sysSuccessOrder.setToLat(to_lat);
                        sysSuccessOrder.setRouteId(routeId);
                        sysSuccessOrder.setToLng(to_lng);
                        sysSuccessOrder.setFromCityId(from_city_id);
                        sysSuccessOrder.setStartingPoiId(starting_poi_id);
                        sysSuccessOrder.setFromName(from_name);
                        sysSuccessOrder.setFromSource(from_source);
                        sysSuccessOrder.setSessId(sess_id);
                        sysSuccessOrder.setFromAddress(from_address);
                        sysSuccessOrder.setOrderDes(order_des);
                        sysSuccessOrder.setPrice(price);
                        sysSuccessOrder.setOrderType("行程");
                        sysSuccessOrder.setTicket(token);
                        sysSuccessOrder.setSysCarInfo(carInfo);
                        System.out.println(sysSuccessOrder);
                        String setUpTime = getOrderSetUpTime(sysSuccessOrder.getTicket(), sysSuccessOrder);
                        JSONObject inviteResult = invitePeersItinerary(sysSuccessOrder, setUpTime, token, secdd_authentication, secdd_challenge);
                        String inviteResult1 = inviteResult.getString("invite_result");
                        String status = "";
                        if (inviteResult1.equals("1")) {
                            System.out.println(start_date);
                            status = "抢单成功";
                            // 设置抢单状态
                            redisTemplate.opsForValue().set(account, "isStart:0");
                            System.out.println("抢单成功" + inviteResult);
                            isOk = true;
                        } else {
                            System.out.println("抢单失败" + inviteResult);
                            String toast = inviteResult.getString("toast");
                            if (toast == null || toast.isEmpty()) {
                                status = "该订单被滴滴指定派送了";
                            } else {
                                status = toast;
                            }
                        }
                        // 存入数据库
                        SysUserOrder sysUserOrder = new SysUserOrder();
                        sysUserOrder.setOrderId(sysSuccessOrder.getOrderId());
                        sysUserOrder.setRouteId(sysUserOrder.getRouteId());
                        sysUserOrder.setOrderStatus(sysSuccessOrder.getOrderId());
                        sysUserOrder.setPrice(sysSuccessOrder.getPrice());
                        sysUserOrder.setPersonNumber(pcDxString);
                        sysUserOrder.setOrderDes(order_des);
                        sysUserOrder.setOrderType("行程");
                        sysUserOrder.setCreateTime(new Date());
                        sysUserOrder.setAccount(account);
                        sysUserOrder.setOrderStatus(status);
                        sysUserOrder.setStartAddress(from_name);
                        sysUserOrder.setEndAddress(to_name);
                        sysUserOrder.setStartDes(from_dist);
                        sysUserOrderMapper.insert(sysUserOrder);
                    }
                    System.out.println(account + "在" + now + "行程刷新到:" + data.getJSONArray("passenger_cards").size());
                }
                return hashMap1;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * @param ticket token
     * @Deprecated 获取自己发布的行程
     */
    public ArrayList<SysSchedule> getMySubmitSchedule(String ticket) {
        OkHttpClient client = new OkHttpClient();
        String token = URLEncoder.encode(ticket);
        String url = "https://api.udache.com/gulfstream/driver-center/v1/dGetSFCHistoryOrderV2?nginx_cors=false&token=" + token
                + "&city_id=3&access_key_id=2&user_role=2&app_version=6.8.12&year=&month=";
        String dd04;
        try {
            dd04 = getDD04(URLEncoder.encode(url), "");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        url = url + "&wsgsig=" + URLEncoder.encode(dd04);
        Request.Builder requestBuilder = new Request.Builder().url(url);

        // 添加自定义请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("Host", "api.udache.com");
        headers.put("Connection", "keep-alive");
        headers.put("sec-ch-ua", "Chromium\";v=\"122\", \"Not(A:Brand\";v=\"24\", \"Android WebView\";v=\"122");
        headers.put("Accept", "application/json, text/plain, */*");
        headers.put("sec-ch-ua-mobile", "?1");
        headers.put("User-Agent", "Mozilla/5.0 (Linux; Android 12; Pixel 3 Build/SP1A.210812.016.C2; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/122.0.6261.119 Mobile Safari/537.36 didi.passenger/6.8.8 FusionKit/2.0.0  OffMode/0");
        headers.put("sec-ch-ua-platform", "Android");
        headers.put("Origin", "https://page.udache.com");
        headers.put("X-Requested-With", "com.sdu.didi.psnger");
        headers.put("Sec-Fetch-Site", "same-site");
        headers.put("Sec-Fetch-Mode", "cors");
        headers.put("Sec-Fetch-Dest", "empty");
        headers.put("Accept-Language", "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7");
        headers.forEach(requestBuilder::addHeader);

        // 构建完整的请求
        Request request = requestBuilder.build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            JSONObject data = jsonObject.getJSONObject("data");
            JSONObject routeCardList = null;
            try {
                routeCardList = data.getJSONObject("route_card_list");
            } catch (Exception e) {
                e.printStackTrace();
            }
            JSONArray underwayList = null;
            try {
                underwayList = routeCardList.getJSONArray("underway_list");
            } catch (Exception e) {
                e.printStackTrace();
            }
            ArrayList<SysSchedule> sysSchedules = new ArrayList<>();
            if (underwayList == null)
                return null;
            for (Object o : underwayList) {
                JSONObject underway = JSONObject.parseObject(o.toString());
                Object order_card_list = underway.getJSONArray("order_card_list").get(0);
                JSONObject orderInfo = JSONObject.parseObject(order_card_list.toString()).getJSONObject("order_info");
                JSONObject status_info = JSONObject.parseObject(order_card_list.toString()).getJSONObject("status_info");
                SysSchedule sysSchedule = new SysSchedule();
                sysSchedule.setRouteId(underway.getString("route_id"));
                sysSchedule.setFromName(orderInfo.getString("from_name"));
                sysSchedule.setToName(orderInfo.getString("to_name"));
                sysSchedule.setSubTitle(status_info.getString("sub_title"));
                if (sysSchedule.getSubTitle().equals("已邀请，待乘客支付"))
                    continue;
                sysSchedules.add(sysSchedule);
            }
            return sysSchedules;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param ticket    token
     * @param auth      用户认证信息
     * @param challenge js算法
     * @Deprecated 取司机车辆信息
     */
    public SysCarInfo getDriverVehicleInformation(String ticket, String auth, String challenge) {
        OkHttpClient client = new OkHttpClient();
        String token = URLEncoder.encode(ticket);
        String url = "https://api.udache.com/gulfstream/driver-center/v1/dGetCarListConfig?access_key_id=2&app_version=6.8.12&ddfp="
                + UUID.randomUUID().toString().replace("-", "") + "&token=" + URLEncoder.encode(ticket);
        String dd04;
        try {
            dd04 = getDD04(URLEncoder.encode(url), "");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Request.Builder requestBuilder = new Request.Builder().url(url);

        // 添加自定义请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("ticket", ticket);
        headers.put("didi-header-omgid", UUID.randomUUID().toString().replace("-", ""));
        headers.put("didi-header-ssuuid", UUID.randomUUID().toString().replace("-", ""));
        headers.put("secdd-authentication:", auth);
        headers.put("Productid", "0");
        headers.put("secdd-challenge", challenge);
        headers.put("didi-header-hint-content", "{\"app_timeout_ms\":3000, \"utc_offset\":\"480\",\"location_cityid\":26," +
                "\"Cityid\":26,\"lang\":\"zh-CN\",\"locale\":\"zh-CN\"}");
        headers.put("TripCountry", "CN");
        headers.put("wsgsig", dd04);
        headers.put("didi_header_rid", getMD5(String.valueOf(Instant.now().toEpochMilli())));
        headers.put("CityId", "26");
        headers.put("User-Agent", "com.sdu.didi.psnger/6.8.12 Rabbit/1.2.6.5 Carrot/1.3.5");
        headers.put("didi-httpdns", "1");
        headers.forEach(requestBuilder::addHeader);
        // 构建完整的请求
        Request request = requestBuilder.build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            JSONObject data = jsonObject.getJSONObject("data");
            JSONArray jsonArray;
            try {
                jsonArray = jsonObject.getJSONObject("data").getJSONArray("car_list");
            } catch (Exception e) {
                return null;
            }
            for (Object o : jsonArray) {
                JSONObject listData = JSONObject.parseObject(o.toString());
                String text = listData.getString("text");
                String gvid = listData.getString("gvid");
                String maxSeatNum = listData.getString("max_seat_num");
                SysCarInfo sysCarInfo = new SysCarInfo();
                sysCarInfo.setText(text);
                sysCarInfo.setGVid(gvid);
                sysCarInfo.setMaxSeatNum(maxSeatNum);
                return sysCarInfo;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    /**
     * @param ticket          token
     * @param sysSuccessOrder 订单实体类
     * @return 返回订单时间
     * @Deprecated 获取订单时间
     */
    public String getOrderSetUpTime(String ticket, SysSuccessOrder sysSuccessOrder) {
        System.out.println();
        OkHttpClient client = new OkHttpClient();
        String token = URLEncoder.encode(ticket);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String url = "https://api.udache.com/gulfstream/driver-center/v1/dGetTimePicker?to_lat="
                + sysSuccessOrder.getToLat() + "&from_lng=" + sysSuccessOrder.getLng() + "&to_lng=" + sysSuccessOrder.getToLng()
                + "&scenes_type=driver_invite_detail&oid=" + sysSuccessOrder.getOrderId() + "&from_lat=" + sysSuccessOrder.getLat()
                + "&access_key_id=2&app_version=6.8.12&ddfp=" + uuid + "&token=" + URLEncoder.encode(ticket);
        String dd04;
        try {
            dd04 = getDD04(URLEncoder.encode(url), "");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Request.Builder requestBuilder = new Request.Builder().url(url);
        // js算法结果
        String challenge = "1,com.sdu.didi.psnger|1.0.28||||0||";
        // 认证信息
        String auth = "c9b8d7050edfdbda045b14aa7b5d4db484ec7abb1fc410d6b830385e4199d4e721eb3ed4272eb36b32a9d8887eee556a27437a569101000001000000";

        // 添加自定义请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("ticket", ticket);
        headers.put("didi-header-omgid", uuid);
        headers.put("didi-header-ssuuid", uuid);
        headers.put("secdd-authentication:", auth);
        headers.put("Productid", "0");
        headers.put("secdd-challenge", challenge);
        headers.put("wsgsig", dd04);
        headers.put("didi_header_rid", uuid);
        headers.put("CityId", "26");
        headers.put("User-Agent", "com.sdu.didi.psnger/6.8.12 Rabbit/1.2.6.5 Carrot/1.3.5");
        headers.put("didi-httpdns", "1");
        headers.forEach(requestBuilder::addHeader);
        // 构建完整的请求
        Request request = requestBuilder.build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            JSONObject data = jsonObject.getJSONObject("data");
            return data.getString("from_date_stamp");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param order     订单实体类
     * @param setUpTime 订单时间
     * @param auth      授权信息
     * @param challenge js算法
     * @Deprecated 邀请同行_跨城
     */
    public JSONObject invitePeersCrossCity(SysSuccessOrder order, String setUpTime,
                                           String ticket,
                                           String auth, String challenge, String cityId) {
        OkHttpClient client = new OkHttpClient();
        String token = URLEncoder.encode(ticket);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        double v = Double.parseDouble(order.getLng());
        v = v - 0.005;
        double v1 = Double.parseDouble(order.getLat());
        v1 = v1 - 0.005;
        String url = "https://api.udache.com/gulfstream/hermesapi/v2/driver/dBusinessInvite?setup_time=" + setUpTime +
                "&from_city_id=" + order.getFromCityId() + "&starting_poi_id=" + order.getStartingPoiId() +
                "&have_friend=0" + "&extra_params=&route_id=" + order.getRouteId() + "&lng=" + String.valueOf(v) +
                "&ddfp=" + uuid + "&from_lng=" + order.getLng() + "&channel=218&oid=" + order.getOrderId() +
                "&type=2&from_name=" + URLEncoder.encode(order.getFromName()) + "&from_source=" + order.getFromSource() +
                "&seat_count=4&sess_id=" + order.getSessId() + "&gvid=" + order.getSysCarInfo().getGVid() + "&from_address=" +
                URLEncoder.encode(order.getFromAddress()) + "&lat=" + String.valueOf(v1) + "&group_key=" + order.getGroupKey() +
                "&from_lat=" + order.getLat() + "&access_key_id=2&app_version=6.8.12&token=" + URLEncoder.encode(ticket);
        String dd04;
        try {
            dd04 = getDD04(URLEncoder.encode(url), "");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Request.Builder requestBuilder = new Request.Builder().url(url);
        // 添加自定义请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("ticket", ticket);
        headers.put("didi-header-omgid", UUID.randomUUID().toString().replace("-", ""));
        headers.put("didi-header-ssuuid", uuid);
        headers.put("secdd-authentication:", auth);
        headers.put("Productid", "0");
        headers.put("secdd-challenge", challenge);
        headers.put("didi-header-hint-content", "{\"app_timeout_ms\":3000, \"utc_offset\":\"480\",\"location_cityid\":26," +
                "\"Cityid\":" + cityId + ",\"lang\":\"zh-CN\",\"locale\":\"zh-CN\"}");
        headers.put("TripCountry", "CN");
        headers.put("wsgsig", dd04);
        headers.put("didi_header_rid", getMD5(String.valueOf(Instant.now().toEpochMilli())));
        headers.put("CityId", cityId);
        headers.put("User-Agent", "com.sdu.didi.psnger/6.8.12 Rabbit/1.2.6.5 Carrot/1.3.5");
        headers.put("didi-httpdns", "1");
        headers.forEach(requestBuilder::addHeader);
        // 构建完整的请求
        Request request = requestBuilder.build();
        System.out.println("订单时间是:" + setUpTime + "\t执行大厅抢单的是:" + order);
        Response response = null;
        try {
            response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            return jsonObject.getJSONObject("data");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param order     订单实体类
     * @param setUpTime 订单时间
     * @param auth      授权信息
     * @param challenge js算法
     * @Deprecated 邀请同行_行程
     */
    public JSONObject invitePeersItinerary(SysSuccessOrder order, String setUpTime,
                                           String ticket,
                                           String auth, String challenge) {

        OkHttpClient client = new OkHttpClient();
        String token = URLEncoder.encode(ticket);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String url = "https://api.udache.com/gulfstream/hermesapi/v2/driver/dInviteCreate?setup_time=" + setUpTime + "&extra_params=&route_id=" +
                order.getRouteId() + "&lng=" + order.getLng() + "&oid=" + order.getOrderId() + "&type=2&lat=" + order.getLat() +
                "&group_key=" + order.getGroupKey() + "&access_key_id=2&app_version=6.8.12&ddfp=" + uuid + "&token=" + URLEncoder.encode(token);
        String dd04;
        try {
            dd04 = getDD04(URLEncoder.encode(url), "");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Request.Builder requestBuilder = new Request.Builder().url(url);
        // 添加自定义请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("ticket", ticket);
        headers.put("didi-header-omgid", UUID.randomUUID().toString().replace("-", ""));
        headers.put("didi-header-ssuuid", uuid);
        headers.put("secdd-authentication:", auth);
        headers.put("Productid", "0");
        headers.put("secdd-challenge", challenge);
        headers.put("wsgsig", dd04);
        headers.put("CityId", "26");
        headers.put("User-Agent", "com.sdu.didi.psnger/6.8.12 Rabbit/1.2.6.5 Carrot/1.3.5");
        headers.put("didi-httpdns", "1");
        headers.forEach(requestBuilder::addHeader);
        // 构建完整的请求
        Request request = requestBuilder.build();
        System.out.println("订单时间是:" + setUpTime + "\t执行行程抢单的是:" + order);
        Response response = null;
        try {
            response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            return jsonObject.getJSONObject("data");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Deprecated 小程序发验证码_初始化
     */
    public String sendCodeWeChatMiniInit() {
        String md5 = getMD5(String.valueOf(Instant.now().toEpochMilli()));
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        HashMap<String, Object> hashMap = new HashMap<>();
        long epochMilli = Instant.now().toEpochMilli();
        hashMap.put("lang", "zh-CN");
        hashMap.put("access_key_id", 9);
        hashMap.put("appversion", "6.8.8");
        hashMap.put("channel", 1100000004);
        hashMap.put("_ds", " ");
        hashMap.put("xpsid", md5);
        hashMap.put("xpsid_root", md5);
        hashMap.put("xoid", UUID.randomUUID().toString());
        hashMap.put("xenv", "wxmp");
        hashMap.put("prod_key", "ut-aggre-homepage");
        hashMap.put("_type", "product");
        hashMap.put("_t", epochMilli);
        hashMap.put("need_page_config", false);
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        String url = "https://api.didi.cn/webx/mp/product/init?_t=" + String.valueOf(epochMilli);
        try {
            url = url + "&wsgsig=" + URLEncoder.encode(getDD04(url, ""));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Host", "api.didi.cn")
                .addHeader("Connection", "keep-alive")
                .addHeader("secdd-authentication", String.valueOf(epochMilli))
                .addHeader("charset", "utf-8")
                .addHeader("didi-header-rid", UUID.randomUUID().toString().replaceAll("-", ""))
                .addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 12; Pixel 3 Build/SP1A.210812.016.C2; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/122.0.6261.120 Mobile Safari/537.36 XWEB/1220067 MMWEBSDK/20240404 MMWEBID/3880 MicroMessenger/8.0.49.2600(0x28003156) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64 MiniProgramEnv/android")
                .addHeader("x-cluster-id", "786")
                .addHeader("content-type", "application/json")
                .addHeader("Accept-Encoding", "gzip,compress,br,deflate")
                .addHeader("secdd-challenge", "3|v1.1.0||||||")
                .addHeader("didi-header-hint-content", "{\"lang\":\"zh-CN\",\"Cityid\":0")
                .addHeader("Referer", "https://servicewechat.com/wxaf35009675aa0b2a/866/page-frame.html")
                .build();

        // 发送请求并获取响应

        try (Response response = client.newCall(request).execute()) {
            assert response.body() != null;
            JSONObject jsonObject = null;
            try {
                jsonObject = JSONObject.parseObject(response.body().string());
            } catch (Exception e) {

            }
            JSONObject data = JSONObject.parseObject(jsonObject.getString("data"));
            String code = jsonObject.getString("code");
            return response.header("secdd-authentication");
        } catch (Exception e) {
            System.out.println(e);
        }
        return null;
    }


    /**
     * @Deprecated 初始完后发送验证码
     */
    public String sendCodeWeChatMini(String param) throws UnsupportedEncodingException, IOException {
        String targetUrl = "https://dev.kdlapi.com/testproxy";
        // 用户名密码认证(私密代理/独享代理)
        final String username = "d1367861993";
        final String password = "2p4n0ufj";

        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        // 读取响应
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            String[] parts = response.toString().split(":");
            if (parts.length >= 2) {
                String ip = parts[0].trim();
                int port = Integer.parseInt(parts[1].trim());

                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, port));

                Authenticator authenticator = new Authenticator() {
                    @Override
                    public Request authenticate(Route route, Response response) throws IOException {
                        String credential = Credentials.basic(username, password);
                        return response.request().newBuilder()
                                .header("Proxy-Authorization", credential)
                                .build();
                    }
                };

                OkHttpClient client = new OkHttpClient.Builder()
                        .proxy(proxy)
                        .proxyAuthenticator(authenticator)
                        .build();
                String requestData = param;
                MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
                RequestBody body = RequestBody.create(mediaType, requestData);
                Request request = new Request.Builder()
                        .url(targetUrl)
                        .url("https://epassport.diditaxi.com.cn/passport/login/v5/codeMT?&wsgsig=dd04-opzKIpzv0Helcs8AzeS%2Bt8xv2y9PNdtJ8dTgXCZVc7FBaXDBgRC4W03Plxr%2BQO1c4Kfe0G3mkAAcKH0R%2BgsjrtpZG7%2FQbBGxuzosZsf%2B0iA%2BQVpk5QIdXj6Xe7ArNHch63TcZt3nd9SXNV1a3X7ADt011vcy")
                        .addHeader("Host", "epassport.diditaxi.com.cn")
                        .addHeader("secdd-authentication", "")
                        .addHeader("charset", "utf-8")
                        .addHeader("mpxlogin-ver", "5.4.30")
                        .addHeader("didi-header-rid", getMD5(String.valueOf(Instant.now().toEpochMilli())))
                        .addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 12; Pixel 3 Build/SP1A.210812.016.C2; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/122.0.6261.120 Mobile Safari/537.36 XWEB/1220067 MMWEBSDK/20240404 MMWEBID/3880 MicroMessenger/8.0.49.2600(0x28003156) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64 MiniProgramEnv/android")
                        .addHeader("content-type", "application/x-www-form-urlencoded")
                        .addHeader("secdd-challenge", "3|v1.1.0||||||")
                        .addHeader("didi-header-hint-content", "{\"lang\":\"zh-CN\",\"Cityid\":\"\"}")
                        .addHeader("Referer", "https://servicewechat.com/wxaf35009675aa0b2a/866/page-frame.html")
                        .post(body)
                        .build();

                Response i_response = client.newCall(request).execute();
                return i_response.body().string();
            }
        } else {
            System.out.println("GET request not worked");
        }
        connection.disconnect();
        return null;
    }

    /**
     * @return 返回ip和端口
     * @Deprecated 获取ip池
     */
    public static String getProxyIp() {
        String url = "https://share.proxy.qg.net/get?key=59CE726B";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                JSONObject jsonObject = JSON.parseObject(response.body().string());
                JSONArray data = jsonObject.getJSONArray("data");
                JSONObject rlt = (JSONObject) data.get(0);
                String server = rlt.getString("server");
                System.out.println(server);
                return server;
            } else {
                System.out.println("Error: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @Deprecated 微信小程序登录获取token
     */
    public String weChatMiniLogin(String url, String param, Map<String, String> header) throws UnsupportedEncodingException, IOException {
        OutputStreamWriter out;
        BufferedReader in = null;
        String result = "";
        URL realUrl = new URL(url);
        // 打开和URL之间的连接
        HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
        //设置超时时间
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(15000);
        // 设置通用的请求属性
        if (header != null) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        conn.setRequestMethod("POST");
        conn.addRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // 获取URLConnection对象对应的输出流
        out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");// utf-8编码
        // 发送请求参数
        out.write(param);

        // flush输出流的缓冲
        out.flush();
        // 定义BufferedReader输入流来读取URL的响应
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf8"));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
        if (out != null) {
            out.close();
        }
        if (in != null) {
            in.close();
        }
        return result;
    }

    /**
     * @return 返回好封装的原始参数
     * @Deprecated 返回一个原始的数据让接口重新调用获取js算法
     */
    private HashMap<String, String> resultMap() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("secdd_challenge", "1,com.sdu.didi.psnger|1.0.28||||0||9fa12aab27a62e2278c538cfd4a2e012");
        hashMap.put("secdd_authentication", "c9b8d7050edfdbda045b14aa7b5d4db484ec7abb1fc410d6b830385e4199d4e721eb3ed4272eb36b32a9d8887eee556a27437a569101000001000000");
        hashMap.put("error", "error");
        return hashMap;
    }

    /**
     * @param input 需要获取的文本
     * @return 返回取出的数据
     * @Deprecated 获取{}中间的所有内容
     */
    public static String extractContent(String input) {
        int start = input.indexOf("{");
        int end = input.indexOf("}");
        if (start != -1 && end != -1 && start < end) {
            return input.substring(start + 1, end);
        }
        return null;
    }

    /**
     * @param input 需要获取的文本
     * @return 返回取出的数据
     * @Deprecated 获取明天 {00:20-00:35}只取中间的35部分
     */
    public static String extractStartTime(String input) {
        int startIndex = input.indexOf("{") + 1;
        int endIndex = input.indexOf("-");
        if (startIndex != -1 && endIndex != -1 && startIndex < endIndex) {
            return input.substring(startIndex, endIndex);
        }
        return null;
    }

    /**
     * @param input 需要获取的文本
     * @return 返回取出的数据
     * @Deprecated 获取明天 {00:20}只取中间的20部分
     */
    public static String extractStartTimeTwo(String input) {
        String pattern = "\\{([0-9]{2}:[0-9]{2})\\}";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(input);
        if (m.find()) {
            return m.group(1);
        } else {
            return null;
        }
    }

    private String parseTime(String orderTime) {
        String time = extractStartTime(orderTime);
        if (time == null) {
            time = extractStartTimeTwo(orderTime);
        }
        LocalDate currentDate = LocalDate.now();
        int year = currentDate.getYear();
        int month = currentDate.getMonthValue();
        String monthString = String.valueOf(month);

        int day = currentDate.getDayOfMonth();
        if (orderTime.contains("明天"))
            day = day + 1;
        if (orderTime.contains("后天"))
            day = day + 2;
        if (orderTime.contains("大后天"))
            day = day + 3;
        if (orderTime.contains("大大后天"))
            day = day + 4;
        String dayString = String.valueOf(day);

        if (monthString.length() < 2) {
            monthString = "0" + monthString;
        }

        if (dayString.length() < 2) {
            dayString = "0" + dayString;
        }

        return year + "-" + monthString + "-" + dayString + " " + time;
    }

}
